<?php
/**
 * Created by PhpStorm.
 * User: LP
 * Date: 2018/4/10
 * Time: 10:50
 */
define("AINONGKEY", 'jXSjmVy2RghVYjPmZ8tjjmuCr483M5vt');
class AiNongpayAction extends Action{
    public function submitAiNongPay($sn, $totalFee, $desc, $retUrl = '',$customerId,$needReturn = 0, $bankNum = ''){
        Session::switchCustomer(0);
        $aiNongModel = M('customer_mall_ainongpay_setting');
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);

        //再次查询订单信息
        $orderInfo = $orderModel->field("sum(price) as price,sum(couponMoney) as couponMoney,sum(purseMoney) as purseMoney,sum(logisticsCost) as logisticsCost")
            ->where(['tempSerialNumber' => $sn])->find();
        $totalFee = $orderInfo['price']+$orderInfo['logisticsCost'];
        if($orderInfo['couponMoney']){
            $totalFee-=$orderInfo['couponMoney'];
        }
        if($orderInfo['purseMoney']){
            $totalFee-=$orderInfo['purseMoney'];
        }
        strlen($desc) > 6 ? $desc = substr($desc,0,6) : '' ;


        //构造要请求的参数数组
        $para_temp = array(
            "version"        => version,
            "txnType"        => txnType,
            "txnSubType"        => txnSubType,
            "bizType"        => bizType,
            "accessType"        => accessType,
            "accessMode"        => accessMode,
            "payType"        => payType,
            "signMethod"        => 'MD5',
            "merOrderId"       	=> $sn,
            "txnTime"        	=> date("YmdHis"),
            "txnAmt"        	=> $totalFee*100,
            "currency"        	=> 'CNY',
            "frontUrl"         	=>  C('SERVER_HOST')."AiNongpay/callBack.json",
            "backUrl"         	=> C('SERVER_HOST')."AiNongpayBack/callBack.json",
            "subject"         	=> $desc,
            "body"         		=> $desc,
            "merResv1"         	=> ''
        );
        empty($bankNum) ? '' : $para_temp['accNo'] = $bankNum;
        $merId = $aiNongModel->where(['customerId' => $customerId])->getField('merId');
        $para_temp['merId'] = $merId;

        $para_filter = paraFilter($para_temp);

        //对待签名参数数组排序
        $para_sort = argSort($para_filter);

        //生成签名结果----------
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $prestr = createLinkstring($para_sort);

        $signature = "";
        switch (strtoupper(trim('MD5'))) {
            case "MD5" :
                $signature = md5Sign($prestr, AINONGKEY);
                break;
            default :
                $signature = "";
        }
        //------------------

        //签名结果与签名方式加入请求提交参数组中
        $para_sort['signMethod'] = strtoupper(trim('MD5'));
        $para_sort['signature'] = $signature;

        //对某些参数值作base64编码
        $config['base64_field']= array('subject','body','respMsg');
        if(empty($config['base64_field']))  return $para_sort;
        foreach($config['base64_field'] as $v){
            isset($para_sort[$v])  &&  ($para_sort[$v]= base64_encode($para_sort[$v]));
        }

        $request_data = createLinkstringUrlencode($para_sort);

        $data['url'] = AINONGPAY_URL."?".$request_data;
        if($needReturn == 1){
            return  $data['url'];
        }
        Output::instance()->object($data);
    }

    public function selectAiNongPay($merOrderId){
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $aiNongModel = M('customer_mall_ainongpay_setting');
        Session::switchCustomer($customerId);
        $para_temp = $aiNongModel->where(['customerId' => 50])->field('key,merId')->find();
        $parameter = array(
            "version"        	=> '1.0.0',
            "txnType"        	=> '00',
            "txnSubType"	    => '01',
            "merId"		        => $para_temp['merId'],
            "merOrderId"		=> $merOrderId,
        );
        $html_text = $this->buildRequestHttp($parameter);
        $config['base64_field']= array('subject','body','respMsg');
        $res_arr=strToArray($html_text,$config['base64_field']);
        if(getSignVeryfy($res_arr,AINONGKEY) ){
            $result = [
                'code'       => 0,
                'msg'    => 'ok',
                'data'    => $res_arr,
            ];
            Output::instance()->object($result);
        } else{
            $result = [
                'code'       => 1,
                'msg'    => '查询失败',
            ];
            Output::instance()->object($result);
        }
    }

    public function refundOrderAiNongPay($cid,$serialNumber, $refundId,
						$refundMoney,$oid,$refundTransactionId){
        Session::switchCustomer(0);
        $aiNongModel = M('customer_mall_ainongpay_setting');
        Session::switchCustomer($cid);
        $para_temp = $aiNongModel->where(['customerId' => $cid])->field('key,merId')->find();
        $parameter = array(
            "version"        		=> '1.0.0',
            "txnType"        		=> '04',
            "txnSubType"		    => '00',
            "merId"			        => $para_temp['merId'],
            "merOrderId"		    => $refundTransactionId,
            "orgMerOrderId"         => $serialNumber,
            "txnTime"        		=>  date("YmdHis"),
            "txnAmt"        		=> $refundMoney,
            "currency"        	    => 'CNY',
            "merResv1"         	    => '',
        );
        $html_text = $this->buildRequestHttp($parameter);
        $config['base64_field']= array('subject','body','respMsg');
        $res_arr=strToArray($html_text,$config['base64_field']);
        log::write('ainong-orderRefund:'.json_encode($res_arr));
        if(getSignVeryfy($res_arr,AINONGKEY) && $res_arr['respCode'] == '0000' ){
            R('Product/refundStatistics', array($oid,$refundMoney));
            ProductOrder::updateOrderRefund($oid, $refundId, true, "");
        } else{
            Log::write("爱农退款失败  ".json_encode($res_arr));
        }
    }

    public function callBack(){
        Log::write('Enter function2 callBack');
        log::write('ainong-get:'.json_encode($_GET));
        log::write('ainong-post:'.json_encode($_POST));
        $sn =  $_POST['merOrderId'];
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderInfo = $orderModel->where("tempSerialNumber = '$sn'")->find();
        $oid = $orderInfo['id'];
        $cid = $orderInfo['fromCustomerId'];
        if($orderInfo['fromUserName']){
            $userName = $orderInfo['fromUserName'];
            cookie("openid_$cid",$userName);
            Session::$user['userName']=$userName;
        }
        Session::switchCustomer($cid);
        $pa = new stdClass();
        $url = WeixinApi::getDomainName();
        if($orderInfo['freebuy']){
            $pa->oid=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=freebuy&method=getView&params={\"oid\":\"$oid\"}";
        }else if($orderInfo['isTeam']){
            $pa->teamId=$orderInfo['teamId'];
            $pa->id=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=tuan&method=getView&params={\"teamId\":\"".$orderInfo['teamId']."\",\"id\":\"$oid\"}";
        }else if($orderInfo['isVirtual']){
            $pa->id=$oid;
            $pa->tplid=1;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=virtualSuccess&params={\"id\":\"$oid\"}";
        }else if($orderInfo['orderType']==3){
            $pa->parId=$orderInfo['playOrderId'];
            $pa->id=$oid;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=allChips&method=indianaSuccess&params={\"id\":\"$oid\",\"parId\":\"".$orderInfo['playOrderId']."\"}";
        }else{
            $pa->id=$oid;
            $pa->tplid=1;
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=orderSuccess&params={\"tplid\":1,\"id\":\"$oid\"}";
        }
        $userInfo['userName']=$orderInfo['fromUserName'];
        $send = Module::callModule("product",$userInfo,"sendNotice",$pa);
        if($send['sendId']){
            $url = $url['SERVER_HOST']."call.html?customerId=$cid&module=product&method=orderSuccess&params={\"tplid\":1,\"id\":\"$oid\",\"sendId\":\"".$send['sendId']."\"}";
        }
        redirect($url);
    }



    /**
     * 建立请求，以模拟远程HTTP的POST请求方式构造并获取处理结果
     * @param $para_temp 请求参数数组
     * @return 处理结果
     */
    public function buildRequestHttp($para_temp) {
        $sResult = '';

        //待请求参数数组字符串
        $request_data = $this->buildRequestParaToString($para_temp);

        //echo $request_data;exit;
        //远程获取数据
        $sResult = curlRequestPOST('http://gpay.chinagpay.com/bas/BgTrans', $this->config['cacert'],$request_data);

        return $sResult;
    }

    /**
     * 生成带urlencode编码的请求参数字符串
     * @param $para_temp  要请求的参数数组
     * @return 要请求的参数字符串
     */
    public function buildRequestParaToString($para_temp) {
        //待请求参数数组
        $para = $this->buildRequestPara($para_temp);

        //把参数组中所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
        $request_data = createLinkstringUrlencode($para);

        return $request_data;
    }

    /**
     * 生成要请求的参数数组
     * @param $para_temp 请求前的参数数组
     * @return 要请求的参数数组
     */
    public function buildRequestPara($para_temp) {
        //除去待签名参数数组中的签名参数
        $para_filter = paraFilter($para_temp);

        //对待签名参数数组排序
        $para_sort = argSort($para_filter);

        //生成签名结果
        $signature = $this->buildRequestMysign($para_sort);

        //签名结果与签名方式加入请求提交参数组中
        $para_sort['signMethod'] = strtoupper(trim('MD5'));
        $para_sort['signature'] = $signature;
        $config['base64_field']= array('subject','body','respMsg');
        //对某些参数值作base64编码
        if(empty($config['base64_field']))  return $para_sort;
        foreach($config['base64_field'] as $v){
            isset($para_sort[$v])  &&  ($para_sort[$v]= base64_encode($para_sort[$v]));
        }
        return $para_sort;
    }

    /**
     * 远程获取数据，POST模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\certificates\cacert.pem'
     * @param $url 指定请求URL完整路径地址
     * @param $cacert_url 指定当前证书的存放路径
     * @param $para 请求的数据包
     * return 远程输出的结果
     */
    public function curlRequestPOST($url, $cacert_url, $para) {

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);
        curl_setopt($curl, CURLOPT_HEADER, 0 );
        curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl,CURLOPT_POST,true);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$para);
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此注释查看异常内容
        curl_close($curl);

        return $responseText;
    }

    /**
     * 生成签名结果
     * @param $para_sort 已排序要签名的数组
     * return 签名结果字符串
     */
    public function buildRequestMysign($para_sort) {
        //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $prestr = createLinkstring($para_sort);
        $signature = "";
        switch (strtoupper(trim('MD5'))) {
            case "MD5" :
                $signature = md5Sign($prestr, AINONGKEY);
                break;
            default :
                $signature = "";
        }

        return $signature;
    }

}
